import cgitb
import os
import sys

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QApplication, QDialog, QStackedWidget
from Ui_XYIotTools import Ui_MainWindow
from About import About
from Update import Update
from SerialTools import SerialTools
from sim import Form_SIM
from globalvar import golbalvar
import logging
import datetime
import traceback
import ctypes


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.arrch()
        # 当前软件版本
        golbalvar._init()
        golbalvar.set_value('curversion', 'V0.44')
        golbalvar.set_value('update_url', 'http://218.206.237.124:19070/xyiottools/')
        golbalvar.set_value('softwareUpdate', 'softwareUpdate.json')
        golbalvar.set_value('update_time', '2024-04-015')
        # "关于"窗口
        self.about_window = About().about_window
        # "升级窗口"
        self.update = Update()
        # "双串口调试工具窗口"
        self.serial_tools_window = SerialTools().serial_tools_window
        # "网络调试工具窗口"

        # "SIM卡调试工具窗口"
        self.sim_search = Form_SIM()
        # log
        self.__Logger = logging.getLogger()
        self.__Logger.info('__init__')
        sys.excepthook = self.HandleException
        self.serial_current_index = 0
        self.net_current_index = 0
        self.sim_current_index = 0
        # 初始化UI
        self.set_ui()

    def arrch(self):
        if sys.platform == 'win32':
            try:
                import ctypes
                # 设置工具栏图标
                ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")
            except:
                print('当前环境不支持调用这个Windows API函数')
        elif sys.platform == 'linux':
            pass
        elif sys.platform == 'darwin':
            pass

    def HandleException(self, excType, excValue, tb):
        currentTime = datetime.datetime.now()
        self.__Logger.info('Timestamp: %s' % (currentTime.strftime("%Y-%m-%d %H:%M:%S")))
        ErrorMessage = traceback.format_exception(excType, excValue, tb)  # 异常信息
        self.__Logger.error('ErrorMessage: %s' % ErrorMessage)  # 将异常信息记录到日志中
        self.__Logger.error('sys.excepthook: %s' % sys.excepthook)
        self.__Logger.error('excType: %s' % excType)
        self.__Logger.error('excValue: %s' % str(excValue))
        self.__Logger.error('tb: %s' % tb)

    def set_ui(self):
        self.setWindowFlag(Qt.WindowMaximizeButtonHint)
        self.ui.action_about.triggered.connect(self.show_about)
        self.ui.action_update.triggered.connect(self.show_update)
        self.serial_current_index = self.ui.stackedWidget.addWidget(self.serial_tools_window)
        self.net_current_index = self.ui.stackedWidget.addWidget(QDialog())
        self.sim_current_index = self.ui.stackedWidget.addWidget(self.sim_search)
        self.ui.pushButton_serialTools.clicked.connect(self.setCurrentSerial)
        self.ui.pushButton_net.clicked.connect(self.setCurrentNet)
        self.ui.pushButton_sim.clicked.connect(self.setCurrentSim)

    def setCurrentSerial(self):
        self.ui.stackedWidget.setCurrentIndex(self.serial_current_index)

    def setCurrentNet(self):
        self.ui.stackedWidget.setCurrentIndex(self.net_current_index)

    def setCurrentSim(self):
        self.ui.stackedWidget.setCurrentIndex(self.sim_current_index)

    def show_about(self):
        self.about_window.show()
        self.about_window.exec()

    def show_update(self):
        self.update.update_check()


if __name__ == '__main__':
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
    app = QApplication(sys.argv)
    MainWindow = MainWindow()
    MainWindow.setWindowFlags(Qt.WindowCloseButtonHint | Qt.MSWindowsFixedSizeDialogHint)
    MainWindow.show()
    sys.exit(app.exec_())
